import { useParams, useLocation, useNavigate, useSearchParams } from 'react-router-dom';

import React, { ComponentType, PropsWithChildren } from 'react';

export interface WithRouterProps<T = ReturnType<typeof useParams>> extends PropsWithChildren {
  history: {
    back: () => void;
    goBack: () => void;
    location: ReturnType<typeof useLocation>;
    push: (url: string, state?: any) => void;
  };
  location: ReturnType<typeof useLocation>;
  params: T;
  searchParams: T;
  navigate: ReturnType<typeof useNavigate>;
}

const withRouter = <P extends object>(Component: ComponentType<P>) => {
  // 相当于给 MyCard组件添加各种props属性，还添加三个重要的属性params,location,navigate
  // eslint-disable-next-line react/display-name
  return (props: Omit<P, keyof WithRouterProps>) => {
    const location = useLocation();
    const params = useParams();
    const searchParams = useSearchParams();
    const navigate = useNavigate();
    const history = {
      back: () => navigate(-1),
      goBack: () => navigate(-1),
      location,
      push: (url: string, state?: any) => navigate(url, { state }),
      replace: (url: string, state?: any) =>
        navigate(url, {
          replace: true,
          state
        })
    };
    return (
      <Component
        history={history}
        location={location}
        navigate={navigate}
        params={params}
        searchParams={searchParams}
        {...(props as P)}
      />
    );
  };
};

export default withRouter;
